// pages/orderDetail/orderDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageData: {
      id: '',
      title: '',
      cover: '',
      price: 0,
      remark: '',
      count: 1,
      amount: 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取从 thingDetail 页面传递过来的商品信息
    this.setData({
      'pageData.id': options.id,
      'pageData.title': decodeURIComponent(options.title),
      'pageData.cover': decodeURIComponent(options.cover),
      'pageData.price': parseFloat(options.price),
      'pageData.amount': parseFloat(options.price)
    });
  },

  // 返回方法
  goBack() {
    wx.navigateBack({
      delta: 1 // 返回上一级页面
    });
  },

  onCountInput(e) {
    const count = parseInt(e.detail.value);
    if (count < 1) {
      count = 1;
    }
    if (count > 10) {
      count = 10;
    }
    this.setData({
      'pageData.count': count,
      'pageData.amount': this.data.pageData.price * count
    });
  },

  onRemarkInput(e) {
    this.setData({
      'pageData.remark': e.detail.value
    });
  },

  decreaseCount() {
    let count = this.data.pageData.count;
    if (count > 1) {
      count--;
      this.setData({
        'pageData.count': count,
        'pageData.amount': this.data.pageData.price * count
      });
    }
  },

  increaseCount() {
    let count = this.data.pageData.count;
    if (count < 10) {
      count++;
      this.setData({
        'pageData.count': count,
        'pageData.amount': this.data.pageData.price * count
      });
    }
  },

  onRemarkInput(e) {
    this.setData({
      'pageData.remark': e.detail.value
    });
  },
  submitOrder() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    if (!userId || !token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    const {
      id,
      count,
      remark
    } = this.data.pageData;
    wx.request({
      url: 'http://127.0.0.1:9100/api/order/create',
      method: 'POST',
      header: {
        'TOKEN': token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId,
        thingId: id,
        count,
        remark
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '订单提交成功',
            icon: 'success'
          });
          // 订单创建成功后，调用 /userOrderList 接口获取最新订单信息
          this.getUserOrderList(userId, '1', id, count);
        } else {
          wx.showToast({
            title: '订单提交失败',
            icon: 'none'
          });
        }
      },
      fail() {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  getUserOrderList(userId, status, thingId, count) {
    const app = getApp();
    const token = app.globalData.token;
    wx.request({
      url: 'http://127.0.0.1:9100/api/order/userOrderList',
      method: 'GET',
      header: {
        'TOKEN': token
      },
      data: {
        userId,
        status
      },
      success: (res) => {
        if (res.data.code === 200) {
          const orderList = res.data.data;
          if (orderList.length > 0) {
            // 假设最新的订单在列表的第一个位置
            const latestOrder = orderList[0];
            const orderId = latestOrder.id;
            console.log('获取到订单 ID:', orderId);
            // 跳转到支付页面
            wx.navigateTo({
              url: `/pages/pay/pay?orderId=${orderId}&thingId=${thingId}&count=${count}&price=${this.data.pageData.price}&amount=${this.data.pageData.amount}&orderTime=${Date.now()}`
            });
          } else {
            wx.showToast({
              title: '未获取到订单信息',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: '获取订单列表失败',
            icon: 'none'
          });
        }
      },
      fail() {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})